#include "ollamaclient.h"
#include <QUrl>
#include <QNetworkRequest>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>

OllamaClient::OllamaClient(QObject *parent) : QObject(parent)
{
    manager = new QNetworkAccessManager(this);
    connect(manager, &QNetworkAccessManager::finished, this, &OllamaClient::onReplyFinished);
}

void OllamaClient::askQuestion(const QString &question)
{
    QUrl url("http://localhost:11434/api/generate"); // 假设 ollama 服务运行在本地
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    // 构建请求体
    QJsonObject json;
    json["model"] = "deepseek-r1:1.5b";
    json["prompt"] = question;
    json["stream"] = true;

    // 添加上下文
    if (!context.isEmpty()) {
        QJsonArray contextArray;
        for (const QString &ctx : context) {
            contextArray.append(ctx);
        }
        json["context"] = contextArray;
    }

    QJsonDocument doc(json);
    QByteArray data = doc.toJson();

    currentReply = manager->post(request, data);
    connect(currentReply, &QNetworkReply::readyRead, this, &OllamaClient::onReadyRead);
}

void OllamaClient::resetContext()
{
    context.clear(); // 清空上下文
}

void OllamaClient::onReplyFinished(QNetworkReply *reply)
{
    if (reply->error() == QNetworkReply::NoError) {
        QByteArray responseData = reply->readAll();
        QJsonDocument doc = QJsonDocument::fromJson(responseData);
        QJsonObject json = doc.object();

        QString response = json["response"].toString();
        QString newContext = json["context"].toString(); // 获取新的上下文

        // 更新上下文
        if (!newContext.isEmpty()) {
            context.append(newContext);
        }

        emit responseReceived(response);
    } else {
        emit errorOccurred(reply->errorString());
    }
    reply->deleteLater();
}

void OllamaClient::onReadyRead()
{
    QByteArray data = currentReply->readAll();
    QJsonDocument doc = QJsonDocument::fromJson(data);
    QJsonObject json = doc.object();
    QString response = json["response"].toString();
    emit streamDataReceived(response);
}
